<template>
  <div class="manager-workers">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">打手管理</h1>
      <p class="page-subtitle">管理打手信息、状态监控和业绩统计</p>
    </div>

    <!-- 统计概览卡片 -->
    <div class="stats-overview">
      <div class="stat-card" v-for="stat in workerStats" :key="stat.label">
        <div class="stat-header">
          <span class="stat-label">{{ stat.label }}</span>
          <div class="stat-icon" :class="stat.iconClass"></div>
        </div>
        <div class="stat-value" :style="{ color: stat.color }">{{ stat.value }}</div>
        <div class="stat-desc">{{ stat.description }}</div>
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索打手姓名、手机号..."
          :prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
      </div>
      <div class="filter-controls">
        <el-select 
          v-model="statusFilter" 
          placeholder="状态筛选" 
          clearable 
          class="status-filter"
          @change="handleStatusFilter"
        >
          <el-option label="全部状态" value="" />
          <el-option label="在线空闲" :value="WorkerStatus.IDLE" />
          <el-option label="工作中" :value="WorkerStatus.WORKING" />
          <el-option label="休息中" :value="WorkerStatus.REST" />
          <el-option label="已离线" :value="WorkerStatus.OFFLINE" />
        </el-select>
        <el-button 
          type="info" 
          size="small" 
          @click="handleResetFilters"
          :disabled="loading"
        >
          重置
        </el-button>
        <el-button 
          type="success" 
          size="small" 
          @click="refreshData"
          :loading="refreshing"
          :disabled="loading"
        >
          刷新
        </el-button>
        <el-button type="primary" :icon="Plus" @click="handleAddWorker" class="add-btn">
          添加打手
        </el-button>
      </div>
    </div>

    <!-- 打手列表 -->
    <div class="workers-grid" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0, 0, 0, 0.3)">
      <div 
        v-for="worker in filteredWorkers" 
        :key="worker.id"
        class="worker-card"
        :class="`status-${worker.status}`"
        @click="handleWorkerDetail(worker)"
      >
        <!-- 状态指示器 -->
        <div class="status-indicator" :class="`status-${worker.status}`">
          <span class="status-dot"></span>
          <span class="status-text">{{ getStatusText(worker.status) }}</span>
        </div>

        <!-- 打手信息 -->
        <div class="worker-info">
          <div class="worker-avatar">{{ worker.nickname?.charAt(0) || worker.realName?.charAt(0) || '?' }}</div>
          <div class="worker-details">
            <h3 class="worker-name">{{ worker.nickname || worker.realName }}</h3>
            <p class="worker-phone">{{ worker.phone }}</p>
            <div class="worker-tags">
              <span v-for="tag in worker.skills" :key="tag" class="skill-tag">{{ tag }}</span>
            </div>
          </div>
        </div>

        <!-- 业绩数据 -->
        <div class="performance-data">
          <div class="performance-item">
            <span class="performance-label">本月订单</span>
            <span class="performance-value">{{ worker.monthlyOrders }}</span>
          </div>
          <div class="performance-item">
            <span class="performance-label">本月收入</span>
            <span class="performance-value">¥{{ worker.monthlyIncome }}</span>
          </div>
          <div class="performance-item">
            <span class="performance-label">评分</span>
            <span class="performance-value rating">{{ worker.rating }}/5.0</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="worker-actions">
          <el-button 
            v-if="worker.status === 'idle'" 
            type="success" 
            size="small" 
            @click.stop="handleAssignOrder(worker)"
          >
            分配订单
          </el-button>
          <el-button 
            v-if="worker.status === 'working'" 
            type="warning" 
            size="small" 
            @click.stop="handleViewCurrentOrder(worker)"
          >
            查看当前订单
          </el-button>
          <el-button type="info" size="small" @click.stop="handleEditWorker(worker)">
            编辑
          </el-button>
          <el-dropdown @command="handleWorkerCommand" trigger="click" @click.stop>
            <el-button type="text" size="small" class="more-btn">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="`view-${worker.id}`">查看详情</el-dropdown-item>
                <el-dropdown-item :command="`history-${worker.id}`">历史记录</el-dropdown-item>
                <el-dropdown-item :command="`performance-${worker.id}`">业绩报表</el-dropdown-item>
                <el-dropdown-item divided :command="`disable-${worker.id}`">暂停接单</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="totalWorkers"
        layout="total, sizes, prev, pager, next, jumper"
        background
        class="custom-pagination"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 添加/编辑打手弹窗 -->
    <WorkerFormDialog
      v-model="showWorkerDialog"
      :worker-data="editingWorker"
      @success="handleWorkerFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Plus, MoreFilled } from '@element-plus/icons-vue'
import { useWorkerStore, WorkerStatus } from '@renderer/store/modules/worker'
import type { Worker } from '@renderer/store/modules/worker'
import WorkerFormDialog from '@renderer/components/worker/WorkerFormDialog.vue'

// 使用打手状态管理
const workerStore = useWorkerStore()

// 计算属性 - 从store获取数据
const workerStats = computed(() => [
  {
    label: '在线打手',
    value: (workerStore.workerStats?.onlineWorkers ?? 0).toString(),
    description: '当前在线可接单',
    color: '#27AE60',
    iconClass: 'online-icon'
  },
  {
    label: '工作中',
    value: (workerStore.workerStats?.workingWorkers ?? 0).toString(),
    description: '正在执行订单',
    color: '#3498DB',
    iconClass: 'working-icon'
  },
  {
    label: '今日活跃',
    value: (workerStore.workerStats?.todayActiveWorkers ?? 0).toString(),
    description: '今日活跃打手数',
    color: '#F39C12',
    iconClass: 'completed-icon'
  },
  {
    label: '总打手数',
    value: (workerStore.workerStats?.totalWorkers ?? 0).toString(),
    description: '店铺总打手数量',
    color: '#9B59B6',
    iconClass: 'total-icon'
  }
])

// 从store获取状态
const {
  workersList,
  loading,
  currentPage,
  pageSize,
  total,
  searchQuery,
  statusFilter,
  filteredWorkers
} = workerStore

// 本地响应式数据
const refreshing = ref(false)
const showWorkerDialog = ref(false)
const editingWorker = ref<Worker | null>(null)

// 计算属性
const totalWorkers = computed(() => total)

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    [WorkerStatus.IDLE]: '空闲',
    [WorkerStatus.WORKING]: '工作中',
    [WorkerStatus.REST]: '休息',
    [WorkerStatus.OFFLINE]: '离线'
  }
  return statusMap[status] || '未知'
}

// 监听搜索和筛选变化，自动重新获取数据
watch([searchQuery, statusFilter], () => {
  loadWorkers()
}, { debounce: 500 })

// 监听分页变化
watch([currentPage, pageSize], () => {
  loadWorkers()
})

// 数据加载方法
const loadWorkers = async () => {
  try {
    await workerStore.fetchWorkerList()
  } catch (error) {
    console.error('加载打手列表失败:', error)
  }
}

const loadStats = async () => {
  try {
    await workerStore.fetchWorkerStats()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 刷新数据
const refreshData = async () => {
  try {
    refreshing.value = true
    await workerStore.refreshData()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    refreshing.value = false
  }
}

// 事件处理方法
const handleAddWorker = () => {
  editingWorker.value = null
  showWorkerDialog.value = true
}

const handleWorkerDetail = async (worker: Worker) => {
  try {
    await workerStore.fetchWorkerDetail(worker.id)
    const name = worker.nickname || worker.realName || '未知'
    ElMessage.success(`查看打手 ${name} 的详细信息`)
    // TODO: 跳转到详情页面或打开弹窗
  } catch (error) {
    // 错误处理已在store中完成
  }
}

const handleAssignOrder = async (worker: Worker) => {
  try {
    // TODO: 获取可分配的订单列表，让用户选择
    const mockOrderId = 1 // 这里应该从订单选择弹窗获取
    await workerStore.assignOrderToWorker(worker.id, mockOrderId)
  } catch (error) {
    // 错误处理已在store中完成
  }
}

const handleViewCurrentOrder = async (worker: Worker) => {
  if (!worker.currentOrder) {
    ElMessage.warning('该打手当前没有执行订单')
    return
  }
  
  try {
    // TODO: 获取当前订单详情并显示
    ElMessage.info(`查看打手 ${worker.nickname || worker.realName} 的当前订单: ${worker.currentOrder}`)
  } catch (error) {
    ElMessage.error('获取当前订单信息失败')
  }
}

const handleEditWorker = (worker: Worker) => {
  editingWorker.value = worker
  showWorkerDialog.value = true
}

const handleWorkerCommand = async (command: string) => {
  const [action, workerIdStr] = command.split('-')
  const workerId = parseInt(workerIdStr)
  const worker = workerStore.workersList.find(w => w.id === workerId)
  
  if (!worker) {
    ElMessage.error('找不到指定的打手')
    return
  }
  
  try {
    switch (action) {
      case 'view':
        await handleWorkerDetail(worker)
        break
        
      case 'history':
        const historyData = await workerStore.fetchWorkerHistory(workerId)
        ElMessage.success(`查看打手 ${worker.nickname || worker.realName} 历史记录`)
        // TODO: 显示历史记录弹窗
        break
        
      case 'performance':
        const performanceData = await workerStore.fetchWorkerPerformance(workerId)
        ElMessage.success(`查看打手 ${worker.nickname || worker.realName} 业绩报表`)
        // TODO: 显示业绩报表弹窗
        break
        
      case 'disable':
        await ElMessageBox.confirm(
          `确定要暂停打手 ${worker.nickname || worker.realName} 的接单吗？`,
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await workerStore.updateWorker(workerId, { isActive: false })
        await loadWorkers() // 重新加载列表
        break
        
      default:
        ElMessage.warning('未知操作')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
    }
  }
}

// 分页处理
const handleCurrentChange = (page: number) => {
  workerStore.setPagination(page, pageSize.value)
}

const handleSizeChange = (size: number) => {
  workerStore.setPagination(1, size)
}

// 搜索处理
const handleSearch = (query: string) => {
  workerStore.setSearchQuery(query)
}

// 筛选处理
const handleStatusFilter = (status: WorkerStatus | '') => {
  workerStore.setStatusFilter(status)
}

// 重置筛选
const handleResetFilters = () => {
  workerStore.resetFilters()
  ElMessage.success('筛选条件已重置')
}

// 表单提交成功处理
const handleWorkerFormSuccess = async (workerData: Worker) => {
  try {
    if (editingWorker.value) {
      // 编辑模式 - 更新打手信息
      await workerStore.updateWorker(editingWorker.value.id, workerData)
    } else {
      // 新增模式 - 添加新打手
      await workerStore.addWorker(workerData)
    }
    
    // 刷新列表和统计数据
    await Promise.all([
      workerStore.fetchWorkerList(),
      workerStore.fetchWorkerStats()
    ])
    
  } catch (error) {
    console.error('处理表单提交失败:', error)
  }
}

// 组件挂载
onMounted(async () => {
  console.log('打手管理页面已加载')
  
  // 显示加载状态
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '加载打手数据...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    // 并行加载统计数据和列表数据
    await Promise.all([
      loadStats(),
      loadWorkers()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载数据失败，请刷新页面重试')
  } finally {
    loadingInstance.close()
  }
})
</script>

<style scoped lang="scss">
.manager-workers {
  padding: 24px;
  padding-bottom: 120px; // 为Dock预留空间
}

// 页面头部
.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: 800;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 12px;
  text-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

.page-subtitle {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

// 统计概览
.stats-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  padding: 24px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.15),
    0 0 60px rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  text-align: center;

  &:hover {
    transform: translateY(-8px);
    box-shadow: 
      0 12px 40px rgba(0, 0, 0, 0.2),
      0 0 80px rgba(255, 255, 255, 0.15);
  }
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stat-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 600;
}

.stat-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  
  &.online-icon { background: linear-gradient(135deg, #27AE60, #2ECC71); }
  &.working-icon { background: linear-gradient(135deg, #3498DB, #5DADE2); }
  &.completed-icon { background: linear-gradient(135deg, #F39C12, #F7DC6F); }
  &.total-icon { background: linear-gradient(135deg, #9B59B6, #BB8FCE); }
}

.stat-value {
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 8px;
}

.stat-desc {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

// 工具栏
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  padding: 16px 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.search-box {
  flex: 1;
  max-width: 300px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.status-filter {
  width: 140px;
}

.add-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 12px;
  font-weight: 600;
}

// 打手网格
.workers-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.worker-card {
  background: rgba(255, 255, 255, 0.12);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.15),
    0 0 60px rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;

  &:hover {
    transform: translateY(-8px);
    box-shadow: 
      0 12px 40px rgba(0, 0, 0, 0.2),
      0 0 80px rgba(255, 255, 255, 0.15);
  }

  &.status-working {
    border-left: 4px solid #3498DB;
  }

  &.status-idle {
    border-left: 4px solid #27AE60;
  }

  &.status-rest {
    border-left: 4px solid #F39C12;
  }

  &.status-offline {
    border-left: 4px solid #95A5A6;
  }
}

// 状态指示器
.status-indicator {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;

  &.status-working {
    background: rgba(52, 152, 219, 0.1);
    color: #3498DB;
  }

  &.status-idle {
    background: rgba(39, 174, 96, 0.1);
    color: #27AE60;
  }

  &.status-rest {
    background: rgba(243, 156, 18, 0.1);
    color: #F39C12;
  }

  &.status-offline {
    background: rgba(149, 165, 166, 0.1);
    color: #95A5A6;
  }
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
}

// 打手信息
.worker-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.worker-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: 700;
}

.worker-details {
  flex: 1;
}

.worker-name {
  font-size: 18px;
  font-weight: 700;
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 4px;
}

.worker-phone {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 8px;
}

.worker-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.skill-tag {
  padding: 2px 8px;
  background: rgba(102, 126, 234, 0.2);
  color: #667eea;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

// 业绩数据
.performance-data {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 16px;
}

.performance-item {
  text-align: center;
  padding: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
}

.performance-label {
  display: block;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 4px;
}

.performance-value {
  display: block;
  font-size: 16px;
  font-weight: 700;
  color: rgba(255, 255, 255, 0.9);

  &.rating {
    color: #F39C12;
  }
}

// 操作按钮
.worker-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  align-items: center;
}

.more-btn {
  color: rgba(255, 255, 255, 0.6) !important;
}

// 分页器
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.custom-pagination {
  :deep(.el-pagination__total),
  :deep(.el-pagination__jump),
  :deep(.el-select .el-input__inner) {
    color: rgba(255, 255, 255, 0.8);
  }

  :deep(.el-pager li) {
    background: rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.8);
    border-radius: 8px;
    margin: 0 2px;

    &.active {
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
    }
  }

  :deep(.btn-prev),
  :deep(.btn-next) {
    background: rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.8);
    border-radius: 8px;
  }
}

// Element Plus 样式覆盖
:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  border-radius: 12px !important;
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5) !important;
}

:deep(.el-select .el-input .el-select__caret) {
  color: rgba(255, 255, 255, 0.6) !important;
}

// 响应式设计
@media (max-width: 1200px) {
  .stats-overview {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .workers-grid {
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  }
}

@media (max-width: 768px) {
  .stats-overview {
    grid-template-columns: 1fr;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
  }
}
</style>